package com.kavian.test.image;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**  
 * @Filename:    MyTools→com.kavian.test.image→CutImage.java
 * @Description:   截取图片
 * @Copyright:   Copyright (c)2012 
 * @Company:     qoocc 
 * @author:   	kavian 
 * @version:    1.0  
 * Create at:  2012-6-29下午1:57:29
 *  
 * Modification History:  
 * Date                      Author           Version     Description  
 * ------------------------------------------------------------------  
 * 2012-6-29下午1:57:29   	     Administrator          1.0        1.0 Version  
 */
public class CutImage {

	/** 截取图片 */
	public static void cutting(File file, int width, int height) {
		cutting(file, 0, 0, width, height);
	}

	/**
	 * @description 截取图片
	 * @param file
	 *            文件名
	 * @param x
	 *            坐标
	 * @param y
	 *            坐标
	 * @param width
	 *            要截取的宽
	 * @param height
	 *            要截取的高
	 * @return kavian 2012-6-27下午5:29:14
	 */
	public static void cutting(File file, int x, int y, int width, int height) {
		try {
			String endName = file.getName();
			endName = endName.substring(endName.lastIndexOf(".") + 1);
			Iterator<ImageReader> readers = ImageIO
					.getImageReadersByFormatName(endName);
			ImageReader reader = (ImageReader) readers.next();
			InputStream is = new FileInputStream(file);
			ImageInputStream iis = ImageIO.createImageInputStream(is);
			reader.setInput(iis, true);
			ImageReadParam param = reader.getDefaultReadParam();
			Rectangle rect = new Rectangle(x, y, width, height);
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			String path = file.getAbsolutePath();
			//path = path.substring(0, path.lastIndexOf("\\"));
			//path = path + "//" + width + "-" + height;
//			File newFile = new File(path);
//			if (!newFile.exists())
//				newFile.mkdirs();
//			newFile = new File(path, file.getName());
//			ImageOutputStream out = ImageIO
//					.createImageOutputStream(new FileOutputStream(file));
			ImageIO.write(bi, endName, file);
//			file = newFile;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String args[]) throws Exception {
		File file = new File("d://2.jpg");
		cutting(file, 150, 30, 400, 400);
	}

}